import { connection } from '../app/database/mysql';
import { commentModel } from './videoPlay.model';
import axios from 'axios';

/**
 * 获取内容
 */
export const getComment = async (movieId: number) => {
  // 准备查询
  let statement = `
    SELECT SQL_CALC_FOUND_ROWS  * FROM comment
  `;
  let where = []
  if (movieId > 0) {
    where.push(`movie_id = ` + movieId)
  }
  if (where.length > 0) {
    statement += ` where `
    for (let i = 0; i < where.length; i++) {
      statement += where[i]
      if (i < where.length - 1) {
        statement += ` and `
      }
    }
  }
  statement += ` ORDER by sortNum DESC, id DESC limit `

  // 执行查询
  const [data] = await connection.promise().query(statement);

  // 提供数据
  return data;
};

/**
 * 按 ID 获取内容
 */
export const getIdComment = async (postId: number) => {
  // 准备查询
  const statement = `
    SELECT * FROM comment
    WHERE id = ?
  `;

  // 执行查询
  const [data] = await connection.promise().query(statement, postId);

  // 提供数据
  return data;
}


/**
 * 创建内容
 */
export const createComment = async (post: commentModel) => {
  // 准备查询
  const statement = `
    INSERT INTO comment
    SET ?
  `;

  // 执行查询
  const [data] = await connection.promise().query(statement, post);

  // 提供数据
  return data;
}

/**
 * 删除内容
 */
export const deleteComment = async (postId: number) => {
  // 准备查询
  const statement = `
    DELETE FROM comment
    WHERE id = ?
  `;

  // 执行查询
  const [data] = await connection.promise().query(statement, postId);

  // 提供数据
  return data;
}

/**
 * 获取视频链接(外)
 */
export const getVideoUrlWai= async (videoUrl: string) => {
  let data: any;
  
  // 准备查询
  const url = `http://play.akax.cn/wxmpjson?vid=` + videoUrl;
  await axios({
    method: "GET",
    url: url,
    headers: {
      withCredentials: true,
      "Access-Control-Allow-Credentials": true,
      'content-type': 'application/json'
      }
    }).then(async res => {
      let videos = await res.data.url_info;
      if (videos && videos.length > 0) {
        data = videos[0].url
      }
    })

  // 提供数据
  return data;
}
